<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>越南时事新闻汉越双语平行语料库 - 语料库详情</title>
    <link rel="stylesheet" href="css/common.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
        }

        /* 顶部导航栏 */
        .header {
            background: #c41e3a;
            color: white;
            padding: 0 20px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 18px;
            font-weight: bold;
        }

        .logo::before {
            content: "🏛️";
            margin-right: 8px;
            font-size: 20px;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-links a {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 4px;
            transition: background 0.3s ease;
        }

        .nav-links a:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .nav-links a.active {
            background: rgba(255, 255, 255, 0.3);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        /* 主内容区域 */
        .main-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        /* 内容布局 */
        .content-layout {
            margin-top: 20px;
            width: 100%;
        }

        /* 面包屑导航 */
        .breadcrumb {
            margin-bottom: 20px;
            font-size: 14px;
            color: #666;
        }

        .breadcrumb a {
            color: #c41e3a;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        /* 语料库信息卡片 */
        .library-info-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            overflow: hidden;
            position: relative;
        }

        .library-info-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: #c41e3a;
        }

        .library-header {
            padding: 30px;
            background: linear-gradient(135deg, #c41e3a 0%, #a0172e 100%);
            color: white;
            position: relative;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .library-info {
            flex: 1;
        }

        .library-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .header-action-btn {
            padding: 8px 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .header-action-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
        }

        .header-action-btn.danger {
            border-color: rgba(220, 53, 69, 0.5);
            background: rgba(220, 53, 69, 0.2);
        }

        .header-action-btn.danger:hover {
            background: rgba(220, 53, 69, 0.3);
            border-color: rgba(220, 53, 69, 0.7);
        }

        .library-title {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
            position: relative;
            z-index: 2;
        }

        .library-subtitle {
            font-size: 16px;
            opacity: 0.9;
            position: relative;
            z-index: 2;
        }

        .library-content {
            padding: 30px;
        }

        .library-meta-inline {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
            padding: 16px 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #c41e3a;
            font-size: 14px;
            line-height: 1.5;
        }

        .meta-inline-item {
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

        .meta-inline-label {
            color: #666;
            font-weight: 500;
        }

        .meta-inline-value {
            color: #333;
            font-weight: 600;
        }

        .meta-inline-separator {
            color: #ccc;
            margin: 0 4px;
            font-weight: 300;
        }

        .library-description {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #c41e3a;
        }

        .description-title {
            font-size: 16px;
            font-weight: bold;
            color: #c41e3a;
            margin-bottom: 10px;
        }

        .description-text {
            color: #666;
            line-height: 1.6;
        }

        /* 操作按钮区域 */
        .action-section {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-bottom: 30px;
        }

        .action-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .action-btn.primary {
            background: #c41e3a;
            color: white;
        }

        .action-btn.primary:hover {
            background: #a0172e;
            transform: translateY(-2px);
        }

        .action-btn.secondary {
            background: #ffd700;
            color: #333;
        }

        .action-btn.secondary:hover {
            background: #e6c200;
            transform: translateY(-1px);
        }

        .action-btn.danger {
            background: #dc3545;
            color: white;
        }

        .action-btn.danger:hover {
            background: #c82333;
            transform: translateY(-2px);
        }


        /* 语料列表区域 */
        .items-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            padding: 30px;
            width: 100%;
            box-sizing: border-box;
        }

        .items-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .items-title {
            font-size: 20px;
            font-weight: bold;
            color: #c41e3a;
        }

        .search-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .search-box {
            position: relative;
            display: flex;
            align-items: center;
        }

        .search-input {
            width: 300px;
            padding: 8px 40px 8px 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }

        .search-input:focus {
            outline: none;
            border-color: #c41e3a;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        .search-input::placeholder {
            color: #999;
        }

        .search-btn {
            position: absolute;
            right: 8px;
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .search-btn:hover {
            color: #c41e3a;
            background: #f8f9fa;
        }

        .clear-search-btn {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            color: #666;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: none;
        }

        .clear-search-btn:hover {
            background: #e9ecef;
            color: #333;
        }

        .clear-search-btn.show {
            display: block;
        }

        .add-item-btn {
            padding: 10px 20px;
            background: #c41e3a;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .add-item-btn:hover {
            background: #a0172e;
            transform: translateY(-1px);
        }

        /* Excel风格的语料表格 */
        .items-table-container {
            margin-top: 20px;
            border: 1px solid #d0d7de;
            border-radius: 6px;
            overflow: hidden;
            background: white;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 16px;
            line-height: 1.6;
        }

        .items-table thead {
            background: #f6f8fa;
            border-bottom: 1px solid #d0d7de;
        }

        .items-table th {
            padding: 12px 16px;
            text-align: left;
            font-weight: 600;
            color: #24292f;
            border-right: 1px solid #d0d7de;
            position: sticky;
            top: 0;
            background: #f6f8fa;
        }

        .items-table th:last-child {
            border-right: none;
        }

        .items-table tbody tr {
            border-bottom: 1px solid #d0d7de;
            transition: background-color 0.15s ease;
        }

        .items-table tbody tr:hover {
            background: #f6f8fa;
        }

        .items-table tbody tr:last-child {
            border-bottom: none;
        }

        .items-table td {
            padding: 12px 16px;
            vertical-align: top;
            border-right: 1px solid #d0d7de;
            color: #24292f;
        }

        .items-table td:last-child {
            border-right: none;
        }

        /* 序号列 */
        .col-index {
            width: 60px;
            text-align: center;
            background: #f6f8fa;
            font-weight: 500;
            color: #656d76;
        }

        /* 源语言列 */
        .col-source {
            width: 45%;
            min-width: 300px;
        }

        /* 目标语言列 */
        .col-target {
            width: 45%;
            min-width: 300px;
        }

        /* 文本内容样式 */
        .text-content {
            font-size: 16px;
            line-height: 1.8;
            word-wrap: break-word;
            white-space: pre-wrap;
        }

        .text-content.source {
            font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
        }

        .text-content.target {
            font-family: 'Times New Roman', serif;
        }

        /* 搜索高亮样式 */
        .search-highlight {
            background-color: rgba(196, 30, 58, 0.15);
            color: #c41e3a;
            font-weight: 500;
            padding: 1px 2px;
            border-radius: 2px;
            box-decoration-break: clone;
            -webkit-box-decoration-break: clone;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #fff3cd;
            color: #856404;
        }

        .status-deleted {
            background: #f8d7da;
            color: #721c24;
        }

        /* 分页 */
        .pagination-section {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }

        .pagination {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            background: white;
            color: #666;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .pagination button:hover {
            background: #c41e3a;
            color: white;
            border-color: #c41e3a;
        }

        .pagination button.active {
            background: #c41e3a;
            color: white;
            border-color: #c41e3a;
        }

        .pagination button:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }

        /* 加载动画 */
        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .loading-spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #c41e3a;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 添加语料模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {
            padding: 24px 24px 0;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 20px;
            font-weight: bold;
            color: #c41e3a;
            margin: 0;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            padding: 0;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .modal-close:hover {
            background: #f0f0f0;
            color: #333;
        }

        .modal-body {
            padding: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        .form-textarea {
            width: 100%;
            min-height: 120px;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            line-height: 1.6;
            resize: vertical;
            transition: border-color 0.3s ease;
            font-family: inherit;
        }

        .form-textarea:focus {
            outline: none;
            border-color: #c41e3a;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        .form-textarea.source {
            font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
        }

        .form-textarea.target {
            font-family: 'Times New Roman', serif;
        }

        .modal-footer {
            padding: 0 24px 24px;
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #c41e3a;
            color: white;
        }

        .btn-primary:hover {
            background: #a0172e;
            transform: translateY(-1px);
        }

        .btn-secondary {
            background: #f8f9fa;
            color: #666;
            border: 1px solid #e0e0e0;
        }

        .btn-secondary:hover {
            background: #e9ecef;
            color: #333;
        }

        /* 批量上传模态框特殊样式 */
        .upload-area {
            border: 2px dashed #d0d7de;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
            margin-bottom: 20px;
        }

        .upload-area:hover {
            border-color: #c41e3a;
            background: #fff5f5;
        }

        .upload-area.dragover {
            border-color: #c41e3a;
            background: #fff5f5;
            transform: scale(1.02);
        }

        .upload-icon {
            font-size: 48px;
            color: #666;
            margin-bottom: 16px;
        }

        .upload-text {
            font-size: 16px;
            color: #666;
            margin-bottom: 8px;
        }

        .upload-hint {
            font-size: 14px;
            color: #999;
        }

        .file-input {
            display: none;
        }

        .format-option {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
            padding: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .format-option:hover {
            background: #f8f9fa;
            border-color: #c41e3a;
        }

        .format-option.selected {
            background: #fff5f5;
            border-color: #c41e3a;
        }

        .format-option input[type="radio"] {
            margin: 0;
        }

        .format-label {
            flex: 1;
            font-weight: 500;
        }

        .format-description {
            font-size: 12px;
            color: #666;
        }

        .selected-file {
            background: #e8f5e8;
            border: 1px solid #28a745;
            border-radius: 6px;
            padding: 12px;
            margin-bottom: 20px;
            display: none;
        }

        .file-info {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .file-name {
            font-weight: 500;
            color: #28a745;
        }

        .file-size {
            font-size: 12px;
            color: #666;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background: #e0e0e0;
            border-radius: 3px;
            overflow: hidden;
            margin-top: 8px;
            display: none;
        }

        .progress-fill {
            height: 100%;
            background: #28a745;
            width: 0%;
            transition: width 0.3s ease;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-container {
                padding: 20px;
            }

            .library-header {
                flex-direction: column;
                align-items: stretch;
                gap: 20px;
            }

            .library-actions {
                justify-content: center;
            }

            .library-title {
                font-size: 24px;
            }

            .library-meta {
                grid-template-columns: 1fr;
                gap: 10px;
            }

            .library-meta-inline {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
                padding: 12px 16px;
            }

            .meta-inline-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 2px;
            }

            .meta-inline-separator {
                display: none;
            }

            .items-header {
                flex-direction: column;
                gap: 15px;
                align-items: stretch;
            }

            .search-container {
                justify-content: center;
            }

            .search-input {
                width: 250px;
            }

            .items-table-container {
                overflow-x: auto;
            }

            .items-table {
                min-width: 600px;
            }

            .col-source,
            .col-target {
                min-width: 250px;
            }

            .nav-links {
                display: none;
            }

            .header-action-btn {
                padding: 6px 12px;
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <header class="header">
        <div class="logo">
            <span>越南时事新闻汉越双语平行语料库</span>
        </div>
        
        <nav class="nav-links">
            <a href="index.html">首页</a>
            <a href="corpus-libraries.html" class="active">语料库</a>
        </nav>

        <div class="user-info">
            <div class="user-avatar">👤</div>
            <span id="userName">用户</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-container">
        <!-- 面包屑导航 -->
        <nav class="breadcrumb">
            <a href="index.html">首页</a> > 
            <a href="corpus-libraries.html">语料库</a> > 
            <span id="breadcrumbTitle">语料库详情</span>
        </nav>

        <!-- 语料库信息卡片 -->
        <section class="library-info-card">
            <div class="library-header">
                <div class="library-info">
                    <h1 class="library-title" id="libraryTitle">语料库名称</h1>
                    <p class="library-subtitle" id="librarySubtitle">语料库描述</p>
                </div>
                <div class="library-actions">
                    <button class="header-action-btn" onclick="editLibrary()">
                        编辑
                    </button>
                    <button class="header-action-btn" onclick="addItem()">
                        添加语料
                    </button>
                    <button class="header-action-btn" onclick="showBatchUploadModal()">
                        批量添加
                    </button>
                    <button class="header-action-btn danger" onclick="deleteLibrary()">
                        删除
                    </button>
                </div>
            </div>
            <div class="library-content">
                <div class="library-meta-inline">
                    <span class="meta-inline-item">
                        <span class="meta-inline-label">领域分类:</span>
                        <span class="meta-inline-value" id="libraryDomain">-</span>
                    </span>
                    <span class="meta-inline-separator">|</span>
                    <span class="meta-inline-item">
                        <span class="meta-inline-label">源语言:</span>
                        <span class="meta-inline-value" id="librarySourceLang">-</span>
                    </span>
                    <span class="meta-inline-separator">|</span>
                    <span class="meta-inline-item">
                        <span class="meta-inline-label">目标语言:</span>
                        <span class="meta-inline-value" id="libraryTargetLang">-</span>
                    </span>
                    <span class="meta-inline-separator">|</span>
                    <span class="meta-inline-item">
                        <span class="meta-inline-label">创建时间:</span>
                        <span class="meta-inline-value" id="libraryCreateTime">-</span>
                    </span>
                    <span class="meta-inline-separator">|</span>
                    <span class="meta-inline-item">
                        <span class="meta-inline-label">更新时间:</span>
                        <span class="meta-inline-value" id="libraryUpdateTime">-</span>
                    </span>
                </div>
            </div>
        </section>

        <!-- 内容布局 -->
        <div class="content-layout">
            <!-- 语料列表区域 -->
            <section class="items-section">
                <div class="items-header">
                    <h2 class="items-title">语料列表</h2>
                    <div class="search-container">
                        <div class="search-box">
                            <input 
                                type="text" 
                                id="searchInput" 
                                class="search-input" 
                                placeholder="搜索语料内容，支持平行语料格式：中文 - 越南语"
                                onkeypress="handleSearchKeyPress(event)"
                                oninput="handleSearchInput(event)"
                            >
                            <button class="search-btn" onclick="performSearch()" title="搜索">
                                🔍
                            </button>
                        </div>
                        <button class="clear-search-btn" id="clearSearchBtn" onclick="clearSearch()">
                            清除搜索
                        </button>
                    </div>
                </div>
                
                <!-- Excel风格的语料表格 -->
                <div class="items-table-container">
                    <table class="items-table">
                        <thead>
                            <tr>
                                <th class="col-index">#</th>
                                <th class="col-source col-source-header">源语言</th>
                                <th class="col-target col-target-header">目标语言</th>
                            </tr>
                        </thead>
                        <tbody id="itemsTableBody">
                            <!-- 语料数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <div class="pagination-section">
                    <div class="pagination" id="pagination">
                        <!-- 分页按钮将通过JavaScript动态生成 -->
                    </div>
                </div>
            </section>
        </div>

        <!-- 加载动画 -->
        <div class="loading" id="loading">
            <div class="loading-spinner"></div>
            <span style="margin-left: 10px;">加载中...</span>
        </div>
    </main>

    <!-- 添加语料模态框 -->
    <div class="modal" id="addItemModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加语料</h3>
                <button class="modal-close" onclick="closeAddItemModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="addItemForm">
                    <div class="form-group">
                        <label class="form-label" for="sourceText" id="sourceTextLabel">源语言 *</label>
                        <textarea 
                            id="sourceText" 
                            name="sourceText" 
                            class="form-textarea source" 
                            placeholder="请输入源语言内容..."
                            required
                        ></textarea>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="targetText" id="targetTextLabel">目标语言 *</label>
                        <textarea 
                            id="targetText" 
                            name="targetText" 
                            class="form-textarea target" 
                            placeholder="请输入目标语言内容..."
                            required
                        ></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeAddItemModal()">
                    取消
                </button>
                <button type="button" class="btn btn-primary" onclick="submitAddItem()">
                    添加语料
                </button>
            </div>
        </div>
    </div>

    <!-- 批量上传模态框 -->
    <div class="modal" id="batchUploadModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">批量上传语料</h3>
                <button class="modal-close" onclick="closeBatchUploadModal()">&times;</button>
            </div>
            <div class="modal-body">
                <!-- 文件格式选择 -->
                <div class="form-group">
                    <label class="form-label">Excel文件格式</label>
                    <div class="format-option selected" onclick="selectFormat('no-index')">
                        <input type="radio" name="format" value="no-index" checked>
                        <div>
                            <div class="format-label">两列格式</div>
                            <div class="format-description" id="twoColumnDesc">第一列：源语言，第二列：目标语言</div>
                        </div>
                    </div>
                    <div class="format-option" onclick="selectFormat('with-index')">
                        <input type="radio" name="format" value="with-index">
                        <div>
                            <div class="format-label">三列格式</div>
                            <div class="format-description" id="threeColumnDesc">第一列：序号，第二列：源语言，第三列：目标语言</div>
                        </div>
                    </div>
                </div>

                <!-- 文件上传区域 -->
                <div class="form-group">
                    <label class="form-label">选择Excel文件</label>
                    <div class="upload-area" onclick="triggerFileInput()" 
                         ondrop="handleDrop(event)" 
                         ondragover="handleDragOver(event)" 
                         ondragleave="handleDragLeave(event)">
                        <div class="upload-icon">📁</div>
                        <div class="upload-text">点击选择文件或拖拽文件到此处</div>
                        <div class="upload-hint">支持 .xlsx, .xls 格式，文件大小不超过10MB</div>
                    </div>
                    <input type="file" id="excelFileInput" class="file-input" 
                           accept=".xlsx,.xls" onchange="handleFileSelect(event)">
                </div>

                <!-- 已选择文件信息 -->
                <div class="selected-file" id="selectedFileInfo">
                    <div class="file-info">
                        <span>📄</span>
                        <span class="file-name" id="fileName"></span>
                        <span class="file-size" id="fileSize"></span>
                    </div>
                    <div class="progress-bar" id="progressBar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeBatchUploadModal()">
                    取消
                </button>
                <button type="button" class="btn btn-primary" id="uploadBtn" onclick="submitBatchUpload()" disabled>
                    开始上传
                </button>
            </div>
        </div>
    </div>

    <script>
        let libraryId = null;
        let currentPage = 1;

        // 页面加载时检查登录状态和获取语料库ID
        window.addEventListener('load', function() {
            try {
                checkLoginStatus();
                if (getLibraryId()) {
                    loadLibraryDetail();
                    loadLibraryItems();
                }
            } catch (error) {
                console.error('页面初始化错误:', error);
                showError('页面加载失败：' + error.message);
            }
        });

        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const user = localStorage.getItem('user');
            
            if (!token) {
                window.location.href = 'login.html';
                return;
            }
            
            if (user) {
                try {
                    const userData = JSON.parse(user);
                    document.getElementById('userName').textContent = userData.username || '用户';
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }
        }

        // 获取语料库ID
        function getLibraryId() {
            const urlParams = new URLSearchParams(window.location.search);
            libraryId = urlParams.get('id');
            
            console.log('URL参数:', window.location.search);
            console.log('获取到的语料库ID:', libraryId);
            
            if (!libraryId) {
                alert('缺少语料库ID参数，请从语料库列表页面进入');
                window.location.href = 'corpus-libraries.html';
                return false;
            }
            return true;
        }

        // 加载语料库详情
        async function loadLibraryDetail() {
            const loading = document.getElementById('loading');
            loading.style.display = 'block';

            try {
                console.log('正在加载语料库详情，ID:', libraryId);
                const response = await fetch(`/corpus/libraries/get/${libraryId}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });

                console.log('API响应状态:', response.status);
                
                if (response.ok) {
                    const result = await response.json();
                    console.log('API响应数据:', result);
                    if (result.code === 200) {
                        displayLibraryDetail(result.data);
                    } else {
                        showError('加载语料库详情失败：' + result.msg);
                    }
                } else {
                    const errorText = await response.text();
                    console.error('API错误响应:', errorText);
                    showError(`网络错误 (${response.status})，请稍后重试`);
                }
            } catch (error) {
                console.error('加载语料库详情错误:', error);
                showError('加载失败：' + error.message);
            } finally {
                loading.style.display = 'none';
            }
        }

        // 显示语料库详情
        function displayLibraryDetail(library) {
            document.getElementById('libraryTitle').textContent = library.name;
            document.getElementById('librarySubtitle').textContent = library.description || '暂无描述';
            document.getElementById('breadcrumbTitle').textContent = library.name;
            document.getElementById('libraryDomain').textContent = library.domain || '未分类';
            document.getElementById('librarySourceLang').textContent = library.sourceLang || '-';
            document.getElementById('libraryTargetLang').textContent = library.targetLang || '-';
            document.getElementById('libraryCreateTime').textContent = formatDate(library.createTime);
            document.getElementById('libraryUpdateTime').textContent = formatDate(library.updateTime);
            
            // 保存语言信息
            librarySourceLang = library.sourceLang || 'zh';
            libraryTargetLang = library.targetLang || 'vi';
            
            // 更新表头显示
            updateTableHeaders();
        }


        // 加载语料列表
        async function loadLibraryItems(page = 1, keyword = '') {
            const loading = document.getElementById('loading');
            loading.style.display = 'block';

            try {
                const params = new URLSearchParams({
                    page: page,
                    size: 10,
                    libraryId: libraryId
                });

                // 解析搜索关键词，支持平行语料搜索格式
                const searchParams = parseSearchKeyword(keyword);
                
                // 添加搜索参数
                if (searchParams.keyword) {
                    params.append('keyword', searchParams.keyword);
                }
                if (searchParams.sourceText) {
                    params.append('sourceText', searchParams.sourceText);
                }
                if (searchParams.targetText) {
                    params.append('targetText', searchParams.targetText);
                }

                const response = await fetch(`/items/list?${params}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 200) {
                        currentPage = page; // 更新当前页码
                        displayLibraryItems(result.data);
                        updatePagination(result.data, page);
                    } else {
                        showError('加载语料列表失败：' + result.msg);
                    }
                } else {
                    showError('网络错误，请稍后重试');
                }
            } catch (error) {
                console.error('加载语料列表错误:', error);
                showError('加载失败，请稍后重试');
            } finally {
                loading.style.display = 'none';
            }
        }

        // 显示语料列表
        function displayLibraryItems(data) {
            const tbody = document.getElementById('itemsTableBody');
            
            if (!data.records || data.records.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="3" style="text-align: center; padding: 40px; color: #666;">
                            <div style="margin-bottom: 16px;">
                                <div style="width: 60px; height: 60px; background: #f0f0f0; border-radius: 8px; margin: 0 auto 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; color: #999;">语</div>
                                <strong>暂无语料数据</strong>
                            </div>
                            <p style="margin: 0; color: #999;">还没有添加任何语料，点击上方按钮添加第一个语料吧！</p>
                        </td>
                    </tr>
                `;
                return;
            }

            // 计算起始序号（基于当前页码）
            const startIndex = (currentPage - 1) * 10;
            
            // 获取当前搜索参数用于高亮
            const searchParams = parseSearchKeyword(currentSearchKeyword);
            
            tbody.innerHTML = data.records.map((item, index) => {
                // 根据语料库的源语言和目标语言决定显示顺序
                let firstColumnText, secondColumnText;
                let firstColumnClass, secondColumnClass;
                
                // 如果源语言是中文，则第一列显示sourceText，第二列显示targetText
                // 如果源语言是越南语，则第一列显示sourceText，第二列显示targetText
                // 关键是sourceText和targetText已经按照语料库的语言设置存储了
                firstColumnText = item.sourceText;
                secondColumnText = item.targetText;
                
                // 应用搜索高亮
                if (searchParams.sourceText && searchParams.targetText) {
                    // 平行语料搜索：分别高亮源语言和目标语言
                    firstColumnText = highlightParallelSearchTerms(firstColumnText, searchParams.sourceText);
                    secondColumnText = highlightParallelSearchTerms(secondColumnText, searchParams.targetText);
                } else if (searchParams.keyword) {
                    // 普通搜索：在两列中都可能高亮
                    firstColumnText = highlightSearchTerms(firstColumnText, searchParams);
                    secondColumnText = highlightSearchTerms(secondColumnText, searchParams);
                }
                
                // 设置字体样式类
                if (librarySourceLang === 'zh') {
                    firstColumnClass = 'source';  // 中文字体
                    secondColumnClass = 'target'; // 越南语字体
                } else {
                    firstColumnClass = 'target';  // 越南语字体
                    secondColumnClass = 'source'; // 中文字体
                }
                
                return `
                    <tr>
                        <td class="col-index">${startIndex + index + 1}</td>
                        <td class="col-source">
                            <div class="text-content ${firstColumnClass}">${firstColumnText}</div>
                        </td>
                        <td class="col-target">
                            <div class="text-content ${secondColumnClass}">${secondColumnText}</div>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 更新分页
        function updatePagination(data, currentPage) {
            const pagination = document.getElementById('pagination');
            const totalPages = Math.ceil(data.total / data.size);
            
            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let paginationHTML = '';
            
            // 上一页按钮
            paginationHTML += `
                <button ${currentPage <= 1 ? 'disabled' : ''} onclick="loadLibraryItems(${currentPage - 1}, '${currentSearchKeyword}')">
                    上一页
                </button>
            `;

            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                paginationHTML += `
                    <button class="${i === currentPage ? 'active' : ''}" onclick="loadLibraryItems(${i}, '${currentSearchKeyword}')">
                        ${i}
                    </button>
                `;
            }

            // 下一页按钮
            paginationHTML += `
                <button ${currentPage >= totalPages ? 'disabled' : ''} onclick="loadLibraryItems(${currentPage + 1}, '${currentSearchKeyword}')">
                    下一页
                </button>
            `;

            pagination.innerHTML = paginationHTML;
        }

        // 编辑语料库
        function editLibrary() {
            window.location.href = `corpus-library-edit.html?id=${libraryId}`;
        }

        // 添加语料
        function addItem() {
            window.location.href = `corpus-item-create.html?libraryId=${libraryId}`;
        }

        // 导出数据
        function exportData() {
            alert('导出功能开发中...');
        }

        // 删除语料库
        function deleteLibrary() {
            if (confirm('确定要删除这个语料库吗？删除后将无法恢复！')) {
                // 实现删除逻辑
                alert('删除功能开发中...');
            }
        }

        // 编辑语料
        function editItem(itemId) {
            window.location.href = `corpus-item-edit.html?id=${itemId}`;
        }

        // 删除语料
        function deleteItem(itemId) {
            if (confirm('确定要删除这个语料吗？删除后将无法恢复！')) {
                // 实现删除逻辑
                alert('删除功能开发中...');
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'active': '活跃',
                'inactive': '非活跃',
                'deleted': '已删除',
                'archived': '已归档'
            };
            return statusMap[status] || status;
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }

        // 退出登录
        async function logout() {
            if (confirm('确定要退出登录吗？')) {
                try {
                    // 调用后端登出接口
                    await fetch('/auth/logout', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('token')}`,
                            'Content-Type': 'application/json'
                        }
                    });
                } catch (error) {
                    console.error('登出请求失败:', error);
                } finally {
                    // 清除本地存储
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    
                    // 跳转到登录页
                    window.location.href = 'login.html';
                }
            }
        }

        // 显示错误消息
        function showError(message) {
            alert('错误：' + message);
        }

        // 编辑语料库
        function editLibrary() {
            window.location.href = `corpus-library-edit.html?id=${libraryId}`;
        }

        // 添加语料 - 打开模态框
        function addItem() {
            document.getElementById('addItemModal').classList.add('show');
            // 清空表单
            document.getElementById('addItemForm').reset();
            // 更新标签和占位符
            updateAddItemModalLabels();
            // 聚焦到第一个输入框
            document.getElementById('sourceText').focus();
        }

        // 更新添加语料模态框的标签
        function updateAddItemModalLabels() {
            const sourceLangName = languageMap[librarySourceLang] || '源语言';
            const targetLangName = languageMap[libraryTargetLang] || '目标语言';
            
            const sourceLabel = document.getElementById('sourceTextLabel');
            const targetLabel = document.getElementById('targetTextLabel');
            const sourceInput = document.getElementById('sourceText');
            const targetInput = document.getElementById('targetText');
            
            if (sourceLabel) {
                sourceLabel.textContent = `${sourceLangName} *`;
            }
            
            if (targetLabel) {
                targetLabel.textContent = `${targetLangName} *`;
            }
            
            if (sourceInput) {
                sourceInput.placeholder = `请输入${sourceLangName}内容...`;
            }
            
            if (targetInput) {
                targetInput.placeholder = `请输入${targetLangName}内容...`;
            }
        }

        // 关闭添加语料模态框
        function closeAddItemModal() {
            document.getElementById('addItemModal').classList.remove('show');
        }

        // 提交添加语料
        async function submitAddItem() {
            const sourceText = document.getElementById('sourceText').value.trim();
            const targetText = document.getElementById('targetText').value.trim();

            // 验证输入
            if (!sourceText) {
                alert('请输入中文原文');
                document.getElementById('sourceText').focus();
                return;
            }

            if (!targetText) {
                alert('请输入越南语译文');
                document.getElementById('targetText').focus();
                return;
            }

            // 准备数据
            const itemData = {
                libraryId: libraryId,
                sourceText: sourceText,
                targetText: targetText
            };

            try {
                // 显示加载状态
                const submitBtn = document.querySelector('.btn-primary');
                const originalText = submitBtn.textContent;
                submitBtn.textContent = '添加中...';
                submitBtn.disabled = true;

                console.log('正在添加语料:', itemData);

                const response = await fetch('/items/create', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(itemData)
                });

                console.log('API响应状态:', response.status);

                if (response.ok) {
                    const result = await response.json();
                    console.log('API响应数据:', result);
                    
                    if (result.code === 200) {
                        alert('语料添加成功！');
                        closeAddItemModal();
                        // 重新加载语料列表，保持搜索状态
                        loadLibraryItems(currentPage, currentSearchKeyword);
                    } else {
                        alert('添加失败：' + result.msg);
                    }
                } else {
                    const errorText = await response.text();
                    console.error('API错误响应:', errorText);
                    alert(`添加失败 (${response.status})，请稍后重试`);
                }
            } catch (error) {
                console.error('添加语料错误:', error);
                alert('添加失败：' + error.message);
            } finally {
                // 恢复按钮状态
                const submitBtn = document.querySelector('.btn-primary');
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }
        }

        // 点击模态框背景关闭
        document.addEventListener('click', function(event) {
            const modal = document.getElementById('addItemModal');
            if (event.target === modal) {
                closeAddItemModal();
            }
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeAddItemModal();
                closeBatchUploadModal();
            }
        });

        // 批量上传相关变量
        let selectedFile = null;
        let selectedFormat = 'no-index';
        
        // 搜索相关变量
        let currentSearchKeyword = '';
        
        // 语料库语言信息
        let librarySourceLang = '';
        let libraryTargetLang = '';
        
        // 语言映射
        const languageMap = {
            'zh': '中文',
            'vi': '越南语'
        };

        // 更新表头显示
        function updateTableHeaders() {
            const sourceHeader = document.querySelector('.col-source-header');
            const targetHeader = document.querySelector('.col-target-header');
            
            if (sourceHeader && targetHeader) {
                sourceHeader.textContent = languageMap[librarySourceLang] || '源语言';
                targetHeader.textContent = languageMap[libraryTargetLang] || '目标语言';
            }
            
            // 更新搜索框占位符
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                const sourceLangName = languageMap[librarySourceLang] || '源语言';
                const targetLangName = languageMap[libraryTargetLang] || '目标语言';
                searchInput.placeholder = `搜索${sourceLangName}或${targetLangName}，支持平行语料格式：${sourceLangName} - ${targetLangName}`;
            }
        }

        // 搜索功能相关函数
        
        // 高亮显示搜索关键词（普通搜索）
        function highlightSearchTerms(text, searchParams) {
            if (!text || !searchParams || !searchParams.keyword) {
                return text;
            }
            
            const keyword = searchParams.keyword.trim();
            if (keyword.length === 0) {
                return text;
            }
            
            // 使用正则表达式进行全局替换，忽略大小写
            const regex = new RegExp(`(${escapeRegExp(keyword)})`, 'gi');
            return text.replace(regex, '<span class="search-highlight">$1</span>');
        }
        
        // 高亮显示平行语料搜索词
        function highlightParallelSearchTerms(text, searchTerm) {
            if (!text || !searchTerm) {
                return text;
            }
            
            const trimmedSearchTerm = searchTerm.trim();
            if (trimmedSearchTerm.length === 0) {
                return text;
            }
            
            // 使用正则表达式进行全局替换，忽略大小写
            const regex = new RegExp(`(${escapeRegExp(trimmedSearchTerm)})`, 'gi');
            return text.replace(regex, '<span class="search-highlight">$1</span>');
        }
        
        // 转义正则表达式特殊字符
        function escapeRegExp(string) {
            return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
        
        // 解析搜索关键词，支持平行语料搜索格式
        function parseSearchKeyword(keyword) {
            if (!keyword || !keyword.trim()) {
                return { keyword: '', sourceText: '', targetText: '' };
            }
            
            const trimmedKeyword = keyword.trim();
            
            // 检查是否是平行语料搜索格式：中文 - 越南语
            // 支持多种分隔符：- | — ｜ 等
            const parallelSearchPattern = /^(.+?)\s*[-|—｜]\s*(.+)$/;
            const match = trimmedKeyword.match(parallelSearchPattern);
            
            if (match) {
                const sourceText = match[1].trim();
                const targetText = match[2].trim();
                
                console.log('检测到平行语料搜索格式:', { sourceText, targetText });
                
                return {
                    keyword: '', // 清空通用关键词
                    sourceText: sourceText,
                    targetText: targetText
                };
            } else {
                // 普通搜索模式
                console.log('使用普通搜索模式:', trimmedKeyword);
                return {
                    keyword: trimmedKeyword,
                    sourceText: '',
                    targetText: ''
                };
            }
        }
        
        // 处理搜索输入
        function handleSearchInput(event) {
            const keyword = event.target.value;
            const clearBtn = document.getElementById('clearSearchBtn');
            
            // 显示或隐藏清除按钮
            if (keyword.trim()) {
                clearBtn.classList.add('show');
            } else {
                clearBtn.classList.remove('show');
            }
            
            // 检测平行语料搜索格式并给出提示
            const searchParams = parseSearchKeyword(keyword);
            if (searchParams.sourceText && searchParams.targetText) {
                // 可以在这里添加视觉提示，表明用户正在使用平行语料搜索
                console.log('平行语料搜索模式激活');
            }
        }

        // 处理搜索框回车键
        function handleSearchKeyPress(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                performSearch();
            }
        }

        // 执行搜索
        function performSearch() {
            const searchInput = document.getElementById('searchInput');
            const keyword = searchInput.value.trim();
            
            currentSearchKeyword = keyword;
            
            // 重置到第一页并执行搜索
            loadLibraryItems(1, keyword);
            
            // 显示清除按钮
            if (keyword) {
                document.getElementById('clearSearchBtn').classList.add('show');
            }
        }

        // 清除搜索
        function clearSearch() {
            const searchInput = document.getElementById('searchInput');
            const clearBtn = document.getElementById('clearSearchBtn');
            
            // 清空搜索框
            searchInput.value = '';
            currentSearchKeyword = '';
            
            // 隐藏清除按钮
            clearBtn.classList.remove('show');
            
            // 重新加载所有数据（这会自动清除高亮效果）
            loadLibraryItems(1, '');
        }

        // 显示批量上传模态框
        function showBatchUploadModal() {
            document.getElementById('batchUploadModal').classList.add('show');
            // 重置状态
            resetBatchUploadModal();
            // 更新格式描述
            updateBatchUploadFormatDescriptions();
        }

        // 更新批量上传格式描述
        function updateBatchUploadFormatDescriptions() {
            const sourceLangName = languageMap[librarySourceLang] || '源语言';
            const targetLangName = languageMap[libraryTargetLang] || '目标语言';
            
            const twoColumnDesc = document.getElementById('twoColumnDesc');
            const threeColumnDesc = document.getElementById('threeColumnDesc');
            
            if (twoColumnDesc) {
                twoColumnDesc.textContent = `第一列：${sourceLangName}，第二列：${targetLangName}`;
            }
            
            if (threeColumnDesc) {
                threeColumnDesc.textContent = `第一列：序号，第二列：${sourceLangName}，第三列：${targetLangName}`;
            }
        }

        // 关闭批量上传模态框
        function closeBatchUploadModal() {
            document.getElementById('batchUploadModal').classList.remove('show');
            resetBatchUploadModal();
        }

        // 重置批量上传模态框
        function resetBatchUploadModal() {
            selectedFile = null;
            selectedFormat = 'no-index';
            document.getElementById('selectedFileInfo').style.display = 'none';
            document.getElementById('progressBar').style.display = 'none';
            document.getElementById('progressFill').style.width = '0%';
            document.getElementById('uploadBtn').disabled = true;
            document.getElementById('excelFileInput').value = '';
            
            // 重置格式选择
            document.querySelectorAll('.format-option').forEach(option => {
                option.classList.remove('selected');
            });
            document.querySelector('.format-option').classList.add('selected');
            document.querySelector('input[name="format"][value="no-index"]').checked = true;
        }

        // 选择文件格式
        function selectFormat(format) {
            selectedFormat = format;
            
            // 更新UI
            document.querySelectorAll('.format-option').forEach(option => {
                option.classList.remove('selected');
            });
            event.currentTarget.classList.add('selected');
            
            // 更新radio按钮
            document.querySelector(`input[name="format"][value="${format}"]`).checked = true;
        }

        // 触发文件选择
        function triggerFileInput() {
            document.getElementById('excelFileInput').click();
        }

        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                validateAndSetFile(file);
            }
        }

        // 处理拖拽相关事件
        function handleDragOver(event) {
            event.preventDefault();
            event.currentTarget.classList.add('dragover');
        }

        function handleDragLeave(event) {
            event.preventDefault();
            event.currentTarget.classList.remove('dragover');
        }

        function handleDrop(event) {
            event.preventDefault();
            event.currentTarget.classList.remove('dragover');
            
            const files = event.dataTransfer.files;
            if (files.length > 0) {
                validateAndSetFile(files[0]);
            }
        }

        // 验证并设置文件
        function validateAndSetFile(file) {
            // 验证文件类型
            const allowedTypes = [
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
                'application/vnd.ms-excel' // .xls
            ];
            
            if (!allowedTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls)$/i)) {
                alert('请选择Excel文件（.xlsx 或 .xls 格式）');
                return;
            }

            // 验证文件大小（10MB）
            if (file.size > 10 * 1024 * 1024) {
                alert('文件大小不能超过10MB');
                return;
            }

            // 设置选中的文件
            selectedFile = file;
            
            // 显示文件信息
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileSize').textContent = formatFileSize(file.size);
            document.getElementById('selectedFileInfo').style.display = 'block';
            document.getElementById('uploadBtn').disabled = false;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 提交批量上传
        async function submitBatchUpload() {
            if (!selectedFile) {
                alert('请先选择文件');
                return;
            }

            const uploadBtn = document.getElementById('uploadBtn');
            const progressBar = document.getElementById('progressBar');
            const progressFill = document.getElementById('progressFill');

            try {
                // 显示进度条
                progressBar.style.display = 'block';
                progressFill.style.width = '0%';
                
                // 禁用按钮
                uploadBtn.textContent = '上传中...';
                uploadBtn.disabled = true;

                // 创建FormData
                const formData = new FormData();
                formData.append('file', selectedFile);
                formData.append('libraryId', libraryId);
                formData.append('hasIndexColumn', selectedFormat === 'with-index');

                console.log('开始批量上传:', {
                    fileName: selectedFile.name,
                    libraryId: libraryId,
                    hasIndexColumn: selectedFormat === 'with-index'
                });

                // 发送请求
                const response = await fetch('/items/batch-upload', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: formData
                });

                console.log('API响应状态:', response.status);

                if (response.ok) {
                    const result = await response.json();
                    console.log('API响应数据:', result);
                    
                    if (result.code === 200) {
                        // 模拟进度条完成
                        progressFill.style.width = '100%';
                        
                        setTimeout(() => {
                            alert(`批量上传成功！共导入 ${result.data.successCount} 条语料`);
                            closeBatchUploadModal();
                            // 重新加载语料列表，保持搜索状态
                            loadLibraryItems(1, currentSearchKeyword);
                        }, 500);
                    } else {
                        alert('上传失败：' + result.msg);
                    }
                } else {
                    const errorText = await response.text();
                    console.error('API错误响应:', errorText);
                    alert(`上传失败 (${response.status})，请稍后重试`);
                }
            } catch (error) {
                console.error('批量上传错误:', error);
                alert('上传失败：' + error.message);
            } finally {
                // 恢复按钮状态
                uploadBtn.textContent = '开始上传';
                uploadBtn.disabled = false;
                progressBar.style.display = 'none';
            }
        }


        // 删除语料库
        async function deleteLibrary() {
            if (!confirm('确定要删除该语料库吗？此操作不可撤销！')) {
                return;
            }

            try {
                const response = await fetch(`/corpus/libraries/delete/${libraryId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 200) {
                        alert('语料库删除成功');
                        window.location.href = 'corpus-libraries.html';
                    } else {
                        showError('删除失败：' + result.msg);
                    }
                } else {
                    showError('网络错误，请稍后重试');
                }
            } catch (error) {
                console.error('删除语料库错误:', error);
                showError('删除失败，请稍后重试');
            }
        }

    </script>
</body>
</html>
